// PlaneList.cpp: implementation of the CPlaneList class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "PlaneList.h"

#include "D3DPlane.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CPlaneList::CPlaneList()
{
	pFirst = pLast = NULL;
	Clear();
}

CPlaneList::~CPlaneList()
{
	Clear();
}


void CPlaneList::Clear()
{
	TotNum = 0;
	pLast = NULL;
	if(pFirst == NULL) return;

	PLANELIST* pNext = pFirst;
	while(pNext)
	{
		PLANELIST* pNow = pNext;
		pNext = pNow->pNextNode;
		delete pNow;
	}

	pFirst = NULL;
	return;
}

BOOL CPlaneList::AddPlane(CD3DPlane* plane)
{
	if(!plane) return FALSE;

	PLANELIST* pNew = new PLANELIST();
	if(pNew==NULL) return FALSE;

	pNew->pPlane = plane;

	TotNum++;

	if(pFirst == NULL) {
		pFirst = pLast = pNew;
		return TRUE;
	}

	pLast->pNextNode = pNew;
	pNew->pPreNode = pLast;
	pLast = pNew;

	return TRUE;
}

BOOL CPlaneList::DelPlane(CD3DPlane* plane)
{
	if(!plane) return FALSE;
	if(TotNum <= 0) return FALSE;

	PLANELIST* pNode = FindPlane(plane);
	if(!pNode) return FALSE;

	if(TotNum>0) TotNum--;

	PLANELIST* pPre = pNode->pPreNode;
	PLANELIST* pNext = pNode->pNextNode;
	
	if(pPre) pPre->pNextNode = pNext;
	else pFirst = pNext;

	if(pNext) pNext->pPreNode = pPre;
	else pLast = pPre;

	if(!pPre && !pNext) pFirst = NULL;

	delete pNode;

	return TRUE;
}

PLANELIST* CPlaneList::FindPlane(CD3DPlane* plane)
{
	PLANELIST* pNext = pFirst;
	while(pNext) {
		if(pNext->pPlane == plane) return pNext;
		pNext = pNext->pNextNode;
	}
	return NULL;
}

void CPlaneList::DestroyAllPlane()
{
	PLANELIST* pNext = pFirst;
	CD3DPlane* plane = NULL;
	while(pNext) {
		plane = pNext->pPlane;
		pNext = pNext->pNextNode;
		if(!plane) continue;
		plane->Destroy();
	}
}
